﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BathhouseService.Areas.WX.Models.HomeVMs;
using BathhouseService.Models.Commonality;
using BathhouseService.Models.SqlModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Mvc.Binders;

namespace BathhouseService.Areas.WX.Controllers
{
    [AllRights]
    [Area("WX")]
    [ActionDescription("手机主要逻辑处理")]
    public class HomeController : BaseController
    {
        #region 公共
        [ActionDescription("首页")]
        public async Task<IActionResult> Index()
        {
            ViewBag.roleName = LoginUserInfo.Roles.Count() > 0 ? LoginUserInfo.Roles[0].RoleName : "游客";
            ViewBag.shufflingfigure = await DC.Set<ShufflingFigure>().ToListAsync();
            ViewBag.notice = await DC.Set<Notice>().OrderByDescending(x => x.ID).Take(3).ToListAsync();
            return View();
        }
        [ActionDescription("个人信息")]
        public async Task<IActionResult> PersonalPage()
        {
            var user = await DC.Set<FrameworkUserBase>().FirstOrDefaultAsync(x => x.ID == LoginUserInfo.Id);
            ViewBag.userinfo = user;
            return View();
        }
        #endregion

        #region 我的服务
        [ActionDescription("我的服务")]
        public async Task<IActionResult> MyService()
        {
            var myService = await DC.Set<ServiceAcquired>()
                .Include(x => x.ValueAddedServices)
                .Where(x => x.FrameworkUserBaseId == LoginUserInfo.Id)
                .ToListAsync();
            return View(myService);
        }
        #endregion

        #region 服务支付
        [ActionDescription("服务支付")]
        public async Task<IActionResult> ServicePayment()
        {
            var userList = await DC.Set<FrameworkUserBase>().Select(x => new
            {
                ID = x.ID,
                RoleName = x.UserRoles.Select(y => y.Role.RoleName).ToSpratedString(null, ","),
                Name = x.Name
            })
                .ToListAsync();
            var sfList = userList.Where(x => x.RoleName == "师傅").Select(x => new
            {
                id = x.ID,
                name = x.Name
            }).ToList();
            var myService = await DC.Set<ServiceAcquired>()
                .Include(x => x.ValueAddedServices)
                .Where(x => x.FrameworkUserBaseId == LoginUserInfo.Id)
                .Select(x => new
                {
                    id = x.ValueAddedServicesId,
                    name = x.ValueAddedServices.Names
                })
                .ToListAsync();
            ViewData["ServicePersonId"] = new SelectList(sfList, "id", "name");
            ViewData["ValueAddedServicesId"] = new SelectList(myService, "id", "name");
            return View();
        }
        [HttpPost]
        [ActionDescription("结账支付")]
        public async Task<IActionResult> ServicePayment(string servicePersonId, int? valueAddedServicesId, int? score)
        {
            if (servicePersonId == null || valueAddedServicesId == null)
            {
                return Content("服务人员或使用服务未选择");
            }
            int fen = score == null ? 5 : (int)score;

            int count = DC.Set<ServiceRecord>().Count();

            ServiceRecord record = new ServiceRecord
            {
                OrderId = AutomaticNumbering.GetNumber(count, "FW."),
                ValueAddedServicesId = (int)valueAddedServicesId,
                ServicePersonId = new Guid(servicePersonId),
                ServicePersonName = DC.Set<FrameworkUserBase>().SingleOrDefault(x => x.ID == new Guid(servicePersonId)).Name,
                CustomerId = LoginUserInfo.Id,
                CustomerName = LoginUserInfo.Name,
                PaymentTime = DateTime.Now,
                Score = fen,
                IsValid = true
            };
            await DC.Set<ServiceRecord>().AddAsync(record);
            int q = await DC.SaveChangesAsync();
            if (q > 0)
            {
                //减少使用次数
                var usersa = await DC.Set<ServiceAcquired>()
                    .SingleOrDefaultAsync(x => x.FrameworkUserBaseId == LoginUserInfo.Id && x.ValueAddedServicesId == (int)valueAddedServicesId);
                var surplus = usersa.RemainingTimes - 1;
                if (surplus < 0)
                {
                    return Content("单项服务已用完，请继续购买套餐卡");
                }
                usersa.RemainingTimes -= 1;
                DC.Set<ServiceAcquired>().Update(usersa);
                await DC.SaveChangesAsync();
                return Content("ok");
            }
            return Content("结账失败");
        }
        [ActionDescription("结账账单")]
        public IActionResult PayBills()
        {
            return View();
        }
        public async Task<IActionResult> PayBillsJson(string str, string end, int? page)
        {

            var list = DC.Set<ServiceRecord>()
                  .Include(x => x.ValueAddedServices)
                  .Where(x => x.CustomerId == LoginUserInfo.Id);
            if (!string.IsNullOrWhiteSpace(str))
            {
                DateTime strD = Convert.ToDateTime(str);
                list = list.Where(x => x.PaymentTime >= strD);
            }
            if (!string.IsNullOrWhiteSpace(end))
            {
                string dt = end + " 23:59:59";
                DateTime endD = Convert.ToDateTime(dt);
                list = list.Where(x => x.PaymentTime <= endD);
            }
            int pages = page == null ? 1 : (int)page;
            var re = await list.OrderByDescending(x => x.ID)
                .Skip((pages - 1) * 5)
                .Take(5)
                .Select(x => new
                {
                    orderid = x.OrderId,
                    service = x.ValueAddedServices.Names + "（" + x.ServicePersonName + "）",
                    dt = x.PaymentTime.ToString("yyyy-MM-dd HH:mm")
                })
                 .ToListAsync();
            return Json(re);
        }
        #endregion

        #region 师傅绩效考核
        [ActionDescription("绩效考核")]
        public async Task<IActionResult> PerformanceAppraisal(string year)
        {
            string cYear = DateTime.Now.Year.ToString();
            if (!string.IsNullOrWhiteSpace(year))
            {
                cYear = year;
            }
            var yearStartEndMonth = DateCalculation.AllStartEndMonth(cYear);
            List<PerformanceAppraisalVM> listPerformanceAppraisalVM = new List<PerformanceAppraisalVM>();
            var tempList = await DC.Set<ServiceRecord>()
                  .Where(x => x.ServicePersonId == LoginUserInfo.Id)
                  .ToListAsync();
            foreach (var item in yearStartEndMonth)
            {
                var temp = tempList.Where(x => x.PaymentTime > item.StartMonth && x.PaymentTime < item.EndMonth);
                PerformanceAppraisalVM vM = new PerformanceAppraisalVM { Mouth = item.StartMonth.Month.ToString() + "月", Count = temp.Count() };
                listPerformanceAppraisalVM.Add(vM);
            }
            ViewBag.year = cYear + "年";
            return View(listPerformanceAppraisalVM);
        }
        [ActionDescription("月度分类记录")]
        public async Task<IActionResult> PerformanceAppraisalDetailed(string yy, string mm)
        {
            string year = yy.Replace("年", "");
            string month = mm.Replace("月", "");
            DateTime date = Convert.ToDateTime(year + "-" + month + "-05");
            DateTime startMonth = DateCalculation.StartMonth(date);
            DateTime endMonth = DateCalculation.EndMonth(date);
            var list = await DC.Set<ServiceRecord>()
                .Include(x => x.ValueAddedServices)
                  .Where(x => x.ServicePersonId == LoginUserInfo.Id)
                  .Where(x => x.PaymentTime > startMonth && x.PaymentTime < endMonth)
                  .GroupBy(x => x.ValueAddedServices.Names)
                  .Select(x => new PerformanceAppraisalDetailedVMs
                  {
                      Name = x.Key,
                      Count = x.Count()
                  })
                  .ToListAsync();
            ViewBag.year = yy + mm;
            return View(list);
        }


        [ActionDescription("服务记录")]
        public IActionResult WorkerServiceRecord()
        {
            return View();
        }
        public async Task<IActionResult> WorkerServiceRecordJson(string str, string end, int? page)
        {
            var list = DC.Set<ServiceRecord>()
                  .Include(x => x.ValueAddedServices)
                  .Where(x => x.ServicePersonId == LoginUserInfo.Id);
            if (!string.IsNullOrWhiteSpace(str))
            {
                DateTime strD = Convert.ToDateTime(str);
                list = list.Where(x => x.PaymentTime >= strD);
            }
            if (!string.IsNullOrWhiteSpace(end))
            {
                string dt = end + " 23:59:59";
                DateTime endD = Convert.ToDateTime(dt);
                list = list.Where(x => x.PaymentTime <= endD);
            }
            int pages = page == null ? 1 : (int)page;
            var re = await list.OrderByDescending(x => x.ID)
                .Skip((pages - 1) * 5)
                .Take(5)
                .Select(x => new
                {
                    orderid = x.OrderId,
                    service = x.ValueAddedServices.Names + "（" + x.CustomerName + "）",
                    dt = x.PaymentTime.ToString("yyyy-MM-dd HH:mm")
                })
                 .ToListAsync();

            return Json(re);
        }


        #endregion

        #region 公告
        [ActionDescription("公告列表")]
        public IActionResult NoticeList()
        {
            return View();
        }
        [ActionDescription("公告列表")]
        public async Task<IActionResult> NoticeListJson(int? page)
        {
            int pages = page == null ? 1 : (int)page;
            var list = await DC.Set<Notice>().OrderByDescending(x => x.ID).Skip((pages - 1) * 11).Take(11).ToListAsync();
            return Json(list);
        }
        [ActionDescription("公告详细信息")]
        public async Task<IActionResult> NoticeDetailed(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var model = await DC.Set<Notice>().SingleOrDefaultAsync(x => x.ID == id);
            if (model == null)
            {
                return NotFound();
            }
            ViewBag.AnnouncementComments =await DC.Set<AnnouncementComments>().Where(x => x.NoticeId == id).OrderByDescending(x=>x.ID).ToListAsync();
            return View(model);
        }

        [ActionDescription("公告评论")]
        [HttpPost]
        public async Task<IActionResult> Comments(string content, int? id)
        {
            if (id == null)
            {
                return Content("系统错误");
            }
            if (string.IsNullOrWhiteSpace(content))
            {
                return Content("请填写评论内容");
            }
            AnnouncementComments comments = new AnnouncementComments
            {
                NoticeId = (int)id,
                UpUserId = LoginUserInfo.Id,
                UpUserName = LoginUserInfo.Name,
                Content = content,
                UpTime = DateTime.Now
            };
            await DC.Set<AnnouncementComments>().AddAsync(comments);
            int x = await DC.SaveChangesAsync();
            if (x>0)
            {
                return Content("ok");
            }
            return Content("系统错误");
        }


        #endregion









    }
}